package com.wusuowei.oauthresource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
// 标识为资源服务器, 所有发往当前服务的请求，都会去请求头里找token，找不到或验证不通过不允许访问
@EnableResourceServer
//开启方法级别权限控制
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //配置当前资源服务器的ID
    private static final String RESOURCE_ID = "product-server";


    @Autowired
    private TokenStore tokenStore;
    /**当前资源服务器的一些配置, 如资源服务器ID **/
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        // 配置当前资源服务器的ID, 会在认证服务器验证(客户端表的resources配置了就可以访问这个服务)
        resources.resourceId(RESOURCE_ID);
                //TODO 可以把配置文件的security配置整个去掉，也要把启动类的@EnableOAuth2Sso注解去掉，不然会报错
                // 在本地配置一个TokenConfig，跟认证服务器一样的类，进行本地token校验
              //  .tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                //不创建session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //资源授权规则
                .authorizeRequests().anyRequest().permitAll();
              //  .antMatchers("/product/**").hasAuthority("product")
                //所有的请求对应访问的用户都要有all范围的权限
             //   .antMatchers("/**").access("#oauth2.hasScope('all')");
    }
}